import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import type { User, LoginCredentials } from './user.interface';

@Injectable()
export class UserService {
  private readonly usersFile = path.join(process.cwd(), 'data', 'users.json');
  private readonly loginRecordsFile = path.join(process.cwd(), 'data', 'login-records.json');

  constructor() {
    // 确保数据目录存在
    const dataDir = path.join(process.cwd(), 'data');
    if (!fs.existsSync(dataDir)) {
      fs.mkdirSync(dataDir, { recursive: true });
    }

    // 初始化文件
    if (!fs.existsSync(this.usersFile)) {
      fs.writeFileSync(this.usersFile, JSON.stringify([]));
    }
    
    if (!fs.existsSync(this.loginRecordsFile)) {
      fs.writeFileSync(this.loginRecordsFile, JSON.stringify([]));
    }
  }

  private readUsers(): User[] {
    const data = fs.readFileSync(this.usersFile, 'utf8');
    return JSON.parse(data);
  }

  private writeUsers(users: User[]): void {
    fs.writeFileSync(this.usersFile, JSON.stringify(users, null, 2));
  }

  private readLoginRecords(): any[] {
    const data = fs.readFileSync(this.loginRecordsFile, 'utf8');
    return JSON.parse(data);
  }

  private writeLoginRecords(records: any[]): void {
    fs.writeFileSync(this.loginRecordsFile, JSON.stringify(records, null, 2));
  }

  findAll(): User[] {
    return this.readUsers();
  }

  findById(id: string): User | undefined {
    const users = this.readUsers();
    return users.find(user => user.id === id);
  }

  findByUsername(username: string): User | undefined {
    const users = this.readUsers();
    return users.find(user => user.username === username);
  }

  create(userData: Partial<User>): User {
    const users = this.readUsers();
    const newUser: User = {
      id: Date.now().toString(),
      username: userData.username || '',
      email: userData.email || '',
      password: userData.password || '',
      role: userData.role || 'user',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    users.push(newUser);
    this.writeUsers(users);
    return newUser;
  }

  update(id: string, userData: Partial<User>): User | null {
    const users = this.readUsers();
    const index = users.findIndex(user => user.id === id);
    if (index === -1) return null;
    
    users[index] = {
      ...users[index],
      ...userData,
      updatedAt: new Date().toISOString(),
    };
    
    this.writeUsers(users);
    return users[index];
  }

  delete(id: string): boolean {
    const users = this.readUsers();
    const initialLength = users.length;
    const filteredUsers = users.filter(user => user.id !== id);
    this.writeUsers(filteredUsers);
    return filteredUsers.length !== initialLength;
  }

  login(credentials: LoginCredentials): { user: User; token: string } | null {
    const user = this.findByUsername(credentials.username);
    if (!user || user.password !== credentials.password) {
      return null;
    }

    // 记录登录信息
    const loginRecords = this.readLoginRecords();
    loginRecords.push({
      userId: user.id,
      loginTime: new Date().toISOString(),
      ip: credentials.ip || 'unknown'
    });
    this.writeLoginRecords(loginRecords);

    // 生成简单token（实际项目中应使用JWT等）
    const token = Buffer.from(`${user.id}:${Date.now()}`).toString('base64');
    
    return { user, token };
  }

  getLoginRecords(userId: string): any[] {
    const records = this.readLoginRecords();
    return records.filter(record => record.userId === userId);
  }
}